import 'whatwg-fetch';
import {
  Helper
} from '../common/helper';
import {
  AppConsts
} from '../store/appConsts';

export class HttpProxy {

  static get(url, params, headers = {}) {

    if (params) {
      let paramsArray = [];
      Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]));
      url += (url.search(/\?/) === -1 ? '?' : '&') + paramsArray.join('&');
    }
    let opt = {
      method: 'get'
    };
    if (headers) {
      opt = Object.assign(opt, {
        headers
      });
    }

    return fetch(url, opt).then(res => res.json());
  }

  static post(url, data, headers = {}, needAuth = true) {
    let defaultHeaders = {
      'Content-Type': 'application/json-patch+json',
      [AppConsts.cookie_tenant_id]: Helper.getTenantId()
    };
    if (needAuth) {
      defaultHeaders[AppConsts.cookie_auth_token] = Helper.getToken()
    }
    let opt = {
      method: 'post',
      headers: Object.assign({}, defaultHeaders, headers),
      body: JSON.stringify(data)
    };

    return fetch(url, opt).then(res => {
      return res.json()
    });
  }

}
